package com.android.lovepick;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TimePicker;

import com.android.lovepick.http.HttpThread;
import com.android.lovepick.map.MapHelper;
import com.android.lovepick.util.BaseUtils;
import com.android.lovepick.util.Constant;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKAddrInfo;

public class OrderActivity extends Activity
{
	private final static String ORDER_TAG = "OrderActivity";

	private EditText edtSrc;
	private EditText edtDest;
	private EditText edtStartDate;
	private EditText edtStartTime;
	private EditText edtFloatTime;
	private EditText edtMoney;
	private ProgressBar progbSrc;
	private ProgressBar progbDest;
	private ListView listView;

	private boolean isSrc = false;
	private boolean isDest = false;
	private boolean isSrcCompleted = false;
	private boolean isDestCompleted = false;
	private boolean isCurrentLoc = false;

	/**
	 * 发布路线按钮对应标识
	 */
	private boolean isRelease = false;

	/**
	 * 推荐路线按钮对应标识
	 */
	private boolean isRecommend = false;

	private ProgressDialog mDialog = null;

	private OrderHandler mHandler;
	private HttpThread mThread;

	private MainApp mApp;
	private MapHelper mMapHelper;

	private String src = Constant.EMPTY_STRING;
	private String dest = Constant.EMPTY_STRING;
	private double slat = 1.0;
	private double slng = 1.0;
	private double dlat = 1.0;
	private double dlng = 1.0;
	private String date = Constant.EMPTY_STRING;
	private String time = Constant.EMPTY_STRING;
	private String goTime = Constant.EMPTY_STRING;
	private String offset = Constant.EMPTY_STRING;
	private String money = Constant.EMPTY_STRING;
	private int iDriver = 0;

	@Override
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.order);
		BaseUtils.setUpActionBar(this);
		findView();

		iDriver = this.getIntent().getIntExtra("iDriver", 0);

		mApp = (MainApp) this.getApplication();

		if (mApp.bmapMan == null)
		{
			mApp.bmapMan = new BMapManager(getApplication());
			mApp.bmapMan.init(MainApp.key, new MainApp.MyGeneraListener());
		}
		mApp.bmapMan.start();
		mDialog = new ProgressDialog(this);
		mHandler = new OrderHandler(this);
		mMapHelper = new MapHelper(mApp.bmapMan, mHandler);
		setListener();
	}

	private void findView()
	{
		edtSrc = (EditText) this.findViewById(R.id.edt_start_point);
		edtDest = (EditText) this.findViewById(R.id.edt_end_point);
		edtStartDate = (EditText) this.findViewById(R.id.edt_start_date);
		edtStartTime = (EditText) this.findViewById(R.id.edt_start_time);
		edtFloatTime = (EditText) this.findViewById(R.id.edt_float_time);
		edtMoney = (EditText) this.findViewById(R.id.edt_payment);
		progbSrc = (ProgressBar) this.findViewById(R.id.progb_start_point);
		progbDest = (ProgressBar) this.findViewById(R.id.progb_end_point);
		listView = (ListView) this.findViewById(R.id.listv_point);
	}

	private void setListener()
	{
		edtSrc.addTextChangedListener(startTextWatcher);
		edtDest.addTextChangedListener(endTextWatcher);
	}

	private TextWatcher startTextWatcher = new TextWatcher()
	{
		public void onTextChanged(CharSequence s, int start, int before,
				int count)
		{
			// TODO Auto-generated method stub
			isSrc = true;
			isDest = false;

			Log.i(ORDER_TAG,
					"start onTextChanged isSrcCompleted:"
							+ String.valueOf(isSrcCompleted));
			if (!isCurrentLoc && !isSrcCompleted)
			{
				Log.i(ORDER_TAG, "start point changed...");
				String startKey = edtSrc.getText().toString();
				Log.i(ORDER_TAG, "on:" + startKey);

				if (!startKey.equals(Constant.EMPTY_STRING))
				{
					progbSrc.setVisibility(View.VISIBLE);
					mMapHelper.searchPoi("北京", startKey);
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after)
		{
			// TODO Auto-generated method stub

		}

		public void afterTextChanged(Editable s)
		{
			// TODO Auto-generated method stub

		}
	};

	private TextWatcher endTextWatcher = new TextWatcher()
	{

		public void onTextChanged(CharSequence s, int start, int before,
				int count)
		{
			isDest = true;
			isSrc = false;
			Log.i(ORDER_TAG, "end point changed...");
			Log.i(ORDER_TAG,
					"end onTextChanged isDestCompleted:"
							+ String.valueOf(isDestCompleted));
			if (!isDestCompleted)
			{
				String endKey = edtDest.getText().toString();
				Log.i(ORDER_TAG, "on:" + endKey);

				if (!endKey.equals(Constant.EMPTY_STRING))
				{
					progbDest.setVisibility(View.VISIBLE);
					mMapHelper.searchPoi("北京", endKey);
				}
			}
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after)
		{
			// TODO Auto-generated method stub
		}

		public void afterTextChanged(Editable s)
		{
			// TODO Auto-generated method stub
		}
	};

	/**
	 * 利用百度地图定位API获取用户当前位置
	 * 位置信息在handler中获取.
	 * 
	 * @param view
	 */
	public void getCurrentLoc(View view)
	{
		if (BaseUtils.checkNetwork(view.getContext()))
		{
			isCurrentLoc = true;
			edtSrc.setText("正在获取当前位置...");
			edtSrc.setFocusable(false);
			progbSrc.setVisibility(View.VISIBLE);
			mMapHelper.getCurrentLocation();
		}
		else
		{
			BaseUtils.showToast(view.getContext(), R.string.net_error);
		}

	}

	private String getOrderEcodeUrl()
	{
		String encodeUrl = null;

		goTime = date + " " + time;
		offset = edtFloatTime.getText().toString();
		money = edtMoney.getText().toString();
		Log.i(ORDER_TAG, "src:" + src);
		Log.i(ORDER_TAG, "slat:" + String.valueOf(slat));
		Log.i(ORDER_TAG, "slng:" + String.valueOf(slng));
		Log.i(ORDER_TAG, "dest:" + dest);
		Log.i(ORDER_TAG, "dlat:" + String.valueOf(dlat));
		Log.i(ORDER_TAG, "dlng:" + String.valueOf(dlng));
		Log.i(ORDER_TAG, "goTime:" + goTime);
		Log.i(ORDER_TAG, "offset:" + offset);
		Log.i(ORDER_TAG, "money:" + money);
		if (checkOrderInfo())
		{
			String tmp = "";
			tmp += ("?test=test");
			tmp += ("&slat=" + String.valueOf(slat));
			tmp += ("&slng=" + String.valueOf(slng));
			tmp += ("&dest=" + dest);
			tmp += ("&src=" + src);
			tmp += ("&dlat=" + String.valueOf(dlat));
			tmp += ("&dlng=" + String.valueOf(dlng));
			tmp += ("&iDriver=" + String.valueOf(iDriver));
			tmp += ("&goTime=" + goTime);
			tmp += ("&offset=" + offset);
			tmp += ("&money=" + money);
			try
			{
				Log.i(ORDER_TAG, tmp);
				encodeUrl = java.net.URLEncoder.encode(tmp, "UTF-8");

			}
			catch (UnsupportedEncodingException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
				encodeUrl = null;
			}
		}
		return encodeUrl;
	}

	public void releaseRoute(View view)
	{
		isRelease = true;
		isRecommend = false;
		String encodeUrl = getOrderEcodeUrl();
		if (encodeUrl != null)
		{
			String url = Constant.HTTP_ORDER_RELEASE_URL + encodeUrl;
			mDialog.setTitle("发布路线");
			mDialog.setMessage("正在发布路线, 请稍候...");
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url,
					null);
			mThread.start();
			mDialog.show();
		}
	}

	public void recommendRoute(View view)
	{
		isRecommend = true;
		isRelease = false;
		String encodeUrl = getOrderEcodeUrl();
		if (encodeUrl != null)
		{
			String url = Constant.HTTP_RECOMMED_ORDER_URL + encodeUrl;
			mDialog.setTitle("获取推荐路线信息");
			mDialog.setMessage("正在获取推荐路线, 请稍候...");
			mThread = new HttpThread(mHandler, Constant.HTTP_METHOD_GET, url,
					null);
			mThread.start();
			mDialog.show();
		}
	}

	private boolean checkOrderInfo()
	{
		if (BaseUtils.checkEmptyString(src))
		{
			BaseUtils.showToast(this, "请输入起点!");
			return false;
		}
		if (BaseUtils.checkEmptyString(dest))
		{
			BaseUtils.showToast(this, "请输入终点!");
			return false;
		}
		if (BaseUtils.checkEmptyString(goTime))
		{
			BaseUtils.showToast(this, "请选择日期和时刻!");
			return false;
		}

		return true;
	}

	public void showDatePickerDialog(View v)
	{
		DatePickerFragment newFragment = DatePickerFragment.newInstance(this);
		newFragment.show(getFragmentManager(), "datePicker");
		Log.i(ORDER_TAG, date);
	}

	public void showTimePickerDialog(View v)
	{
		TimePickerFragment newFragment = TimePickerFragment.newInstance(this);
		newFragment.show(getFragmentManager(), "timePicker");
		Log.i(ORDER_TAG, time);
		// txtDateTime.setText(date + " " + time);
	}

	public static class TimePickerFragment extends DialogFragment implements
			OnTimeSetListener
	{
		private OrderActivity mActivity;

		public static TimePickerFragment newInstance(OrderActivity activity)
		{
			TimePickerFragment fragment = new TimePickerFragment();
			// mActivity = activity;
			Bundle bundle = new Bundle();
			bundle.putSerializable("activity", (Serializable) activity);
			fragment.setArguments(bundle);
			return fragment;
		}

		@Override
		public Dialog onCreateDialog(Bundle bundle)
		{
			mActivity = (OrderActivity) getArguments().getSerializable(
					"activity");
			Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					DateFormat.is24HourFormat(getActivity()));
		}

		public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute)
		{
			// TODO Auto-generated method stub
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH,
					timePicker.getCurrentHour(), timePicker.getCurrentMinute());
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
			mActivity.time = sdf.format(calendar.getTime());
			mActivity.edtStartTime.setText(mActivity.time);
		}
	}

	public static class DatePickerFragment extends DialogFragment implements
			OnDateSetListener
	{
		private OrderActivity mActivity;

		public static DatePickerFragment newInstance(OrderActivity activity)
		{
			DatePickerFragment fragment = new DatePickerFragment();
			Bundle bundle = new Bundle();
			bundle.putSerializable("activity", (Serializable) activity);
			fragment.setArguments(bundle);
			return fragment;
		}

		@Override
		public Dialog onCreateDialog(Bundle bundle)
		{
			mActivity = (OrderActivity) getArguments().getSerializable(
					"activity");
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
				int dayOfMonth)
		{
			// TODO Auto-generated method stub
			final Calendar calendar = Calendar.getInstance();
			calendar.set(datePicker.getYear(), datePicker.getMonth(),
					datePicker.getDayOfMonth());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			mActivity.date = sdf.format(calendar.getTime());
			mActivity.edtStartDate.setText(mActivity.date);
		}
	}

	public static class OrderHandler extends Handler
	{
		private final String ORDER_HANDLER_TAG = "OrderHandler";
		private final WeakReference<OrderActivity> mReference;
		private OrderActivity mActivity;

		public OrderHandler(OrderActivity activity)
		{
			mReference = new WeakReference<OrderActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg)
		{
			mActivity = mReference.get();
			switch (msg.what)
			{
				case Constant.MSG_POISEARCH_COMPLETE:

					final List<Map<String, Object>> list = mActivity.mMapHelper
							.getPoiList();

					if (list != null)
					{
						SimpleAdapter adapter = new SimpleAdapter(
								mReference.get(), list, R.layout.poi_list,
								new String[] { "poi_name", "poi_addr" },
								new int[] { R.id.list_poi_name,
										R.id.list_poi_addr });
						mActivity.listView.setAdapter(adapter);
						RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mActivity.listView
								.getLayoutParams();
						if (mActivity.isSrc)
						{
							params.addRule(RelativeLayout.BELOW, R.id.rel_start);
						}
						else if (mActivity.isDest)
						{
							params.addRule(RelativeLayout.BELOW, R.id.rel_end);
						}
						mActivity.listView.setVisibility(View.VISIBLE);
						mActivity.listView
								.setOnItemClickListener(new AdapterView.OnItemClickListener()
								{

									public void onItemClick(
											AdapterView<?> arg0, View arg1,
											int arg2, long arg3)
									{
										// TODO Auto-generated method stub
										Log.i(ORDER_HANDLER_TAG, "listItem:"
												+ list.get(arg2).toString());

										// 对应于起点和终点的查询, 当listview中的某一项被按下时,
										// 显示这一项.
										// 每一次查询只可能对应起点或终点中的一种情况.
										if (mActivity.isSrc)
										{
											mActivity.isSrcCompleted = true;
											mActivity.src = list.get(arg2)
													.get("poi_name").toString();
											mActivity.edtSrc.setText(list
													.get(arg2).get("poi_name")
													.toString());
											GeoPoint srcGeo = (GeoPoint) list
													.get(arg2).get("poi_geo");
											mActivity.slat = ((double) srcGeo
													.getLatitudeE6()) / 1E6;
											mActivity.slng = ((double) srcGeo
													.getLongitudeE6()) / 1E6;

											mActivity.isSrcCompleted = false;
											Log.i(ORDER_HANDLER_TAG,
													"onItemClick isSrcCompleted:"
															+ String.valueOf(mActivity.isSrcCompleted));

										}
										else if (mActivity.isDest)
										{
											mActivity.isDestCompleted = true;
											mActivity.dest = list.get(arg2)
													.get("poi_name").toString();
											mActivity.edtDest.setText(list
													.get(arg2).get("poi_name")
													.toString());
											GeoPoint destGeo = (GeoPoint) list
													.get(arg2).get("poi_geo");
											mActivity.dlat = ((double) destGeo
													.getLatitudeE6())
													/ ((double) (1E6));
											mActivity.dlng = ((double) destGeo
													.getLongitudeE6())
													/ ((double) (1E6));
											mActivity.isDestCompleted = false;
											Log.i(ORDER_HANDLER_TAG,
													"onItemClick isDestCompleted:"
															+ String.valueOf(mActivity.isDestCompleted));

										}

										mActivity.listView
												.setVisibility(View.INVISIBLE);
									}
								});
					}
					else
					{
						Log.i(ORDER_HANDLER_TAG, "poiList null...");
					}

					mActivity.progbSrc.setVisibility(View.INVISIBLE);
					mActivity.progbDest.setVisibility(View.INVISIBLE);
					break;

				case Constant.MSG_ADDRSEARCH_COMPLETE:
					MKAddrInfo addrResult = mActivity.mMapHelper.getAddrInfo();
					if (addrResult != null)
					{
						String strAddr = addrResult.strAddr;
						Log.i(ORDER_HANDLER_TAG, "current location:" + strAddr);
						mActivity.edtSrc.setText(strAddr);
						mActivity.src = strAddr;
					}
					else
					{
						Log.i(ORDER_HANDLER_TAG, "strAddr null...");
						BaseUtils.showToast(mReference.get(),
								"Failed to get current location...");
					}
					mActivity.progbSrc.setVisibility(View.INVISIBLE);
					mActivity.isCurrentLoc = false;
					mActivity.edtSrc.setFocusableInTouchMode(true);
					break;

				case Constant.MSG_HTTP_SUCCESS:
					Log.i(ORDER_HANDLER_TAG, "get http result");
					String result = msg.getData().getString("http_result");
					Log.i(ORDER_HANDLER_TAG, result);
					if (result.startsWith("[{"))
					{
						mActivity.mDialog.dismiss();

						boolean releaseOrRecommend = false;
						if (mActivity.isRelease)
						{
							// isRelease为true则表明用户点击了发布路线按钮
							BaseUtils.showToast(mReference.get(), "发布路线成功!");
							releaseOrRecommend = false;
						}
						else if (mActivity.isRecommend)
						{
							// isRecommend为true则表明用户点击了推荐路线按钮
							// 返回的是推荐的路线, 同时将用户填写的自己的订单信息保存.
							BaseUtils.showToast(mReference.get(), "获取推荐路线成功!");
							releaseOrRecommend = true;
							Log.i(ORDER_HANDLER_TAG,
									"save my current order infos");
							SharedPreferences myCurrentOrderPrefs = mReference
									.get().getSharedPreferences(
											Constant.PREFS_MY_CURRENT_ORDER,
											Context.MODE_PRIVATE);
							SharedPreferences.Editor editor = myCurrentOrderPrefs
									.edit();
							editor.putBoolean("isRecommend", true);
							editor.putString("src", mActivity.src);
							editor.putString("slat",
									String.valueOf(mActivity.slat));
							editor.putString("slng",
									String.valueOf(mActivity.slng));
							editor.putString("dest", mActivity.dest);
							editor.putString("dlat",
									String.valueOf(mActivity.dlat));
							editor.putString("dlng",
									String.valueOf(mActivity.dlng));
							editor.putInt("iDriver", mActivity.iDriver);
							editor.putString("offset", mActivity.offset);
							editor.putString("goTime", mActivity.goTime);
							editor.putString("money", mActivity.money);
							editor.commit();
						}

						Intent intent = new Intent(mReference.get(),
								MyOrderActivity.class);
						intent.putExtra("myorder", result);
						intent.putExtra("iDriver", mActivity.iDriver);
						intent.putExtra("release_or_recommend",
								releaseOrRecommend);
						mReference.get().startActivity(intent);
						mReference.get().finish();
					}
					else
					{
						mActivity.mDialog.dismiss();
						if (mActivity.isRelease)
						{
							BaseUtils
									.showToast(mReference.get(), "发布路线失败!请重试!");
						}
						else if (mActivity.isRecommend)
						{
							BaseUtils.showToast(mReference.get(),
									"获取推荐路线失败!请重试!");
						}
					}

					break;

				case Constant.MSG_HTTP_ERROR:
					Log.i(ORDER_HANDLER_TAG, "http error...");
					BaseUtils.showToast(mReference.get(), "无法连接服务器!");
					mActivity.mDialog.dismiss();
					break;

				default:
					break;
			}
		}
	}
}